package com.grf.kafka.java.serializer;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.common.serialization.Deserializer;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * @author grf
 * @apiNote 用户序列化
 * @sinec 2024/10/25
 */
@Slf4j
public class UserDeserializer implements Deserializer<User> {
    @Override
    public User deserialize(String s, byte[] data) {
        User user = new User();
        ByteBuffer dataBuffer = ByteBuffer.allocate(data.length);
        dataBuffer.put(data);
        dataBuffer.flip();
        long id = dataBuffer.getLong();
        // log.info("id: {}", id);
        user.setId(id);
        int age = dataBuffer.getInt();
        // log.info("age: {}", age);
        user.setAge(age);
        int sex = dataBuffer.getInt();
        // log.info("sex: {}", sex);
        user.setSex(sex);
        int nameLength = dataBuffer.getInt();
        String name = new String(data,20,nameLength, StandardCharsets.UTF_8).trim();
        // 老师讲解使用，但是乱码
        // String name = new String(dataBuffer.get(data,20, nameLength).array()).trim();
        // log.info("name: {}", name);
        user.setName(name);
        return user;
    }
}
